package org.i9.slb.platform.anseko.provider.task;

import org.i9.slb.platform.anseko.provider.utils.FileCommandUtil;
import org.i9.slb.platform.anseko.common.BusinessException;
import org.i9.slb.platform.anseko.common.ErrorCode;
import org.i9.slb.platform.anseko.common.dubbo.DubboResult;
import org.i9.slb.platform.anseko.downstream.dto.param.FileCommandParamDto;
import org.i9.slb.platform.anseko.downstream.dto.result.CommandExecuteReDto;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * shell命令执行任务（批量）
 *
 * @author R12
 * @version 1.0
 * @date 2018/8/30 17:12
 */
public class FileCommandExecuteBatchTask implements Callable<DubboResult<List<CommandExecuteReDto>>> {

    private List<FileCommandParamDto> fileCommandParamDtos;

    public FileCommandExecuteBatchTask(List<FileCommandParamDto> fileCommandParamDtos) {
        this.fileCommandParamDtos = fileCommandParamDtos;
    }

    @Override
    public DubboResult<List<CommandExecuteReDto>> call() throws Exception {
        DubboResult<List<CommandExecuteReDto>> dubboResult = new DubboResult<List<CommandExecuteReDto>>();
        if (fileCommandParamDtos.isEmpty()) {
            dubboResult.setRe(new ArrayList<CommandExecuteReDto>());
            return dubboResult;
        }
        List<CommandExecuteReDto> commandExecuteReDtos = new ArrayList<CommandExecuteReDto>();
        for (FileCommandParamDto fileCommandParamDto : fileCommandParamDtos) {
            try {
                CommandExecuteReDto commandExecuteReDto = FileCommandUtil.fileExecuteLocal(fileCommandParamDto);
                commandExecuteReDtos.add(commandExecuteReDto);
            } catch (BusinessException e) {
                dubboResult.setCode(e.getResult());
                dubboResult.setMsg(e.getMessage());
            } catch (Exception e) {
                dubboResult.setCode(ErrorCode.UNKOWN_ERROR);
            }
            if (dubboResult.getCode().intValue() != ErrorCode.SUCCESS.intValue()) {
                return dubboResult;
            }
        }
        dubboResult.setRe(commandExecuteReDtos);
        return dubboResult;
    }
}
